package com.park.web.util.poi;

import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hssf.converter.ExcelToHtmlConverter;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import com.park.web.util.close.CloseUtil;
public class PoiUtil {

	private PoiUtil(){}
	private static final  Logger logger = LoggerFactory.getLogger(PoiUtil.class);

	 /**
     * Excel 转为　HTML
     */
    public static void excelToHtml(String exelFileName, String htmlFilePath){
        try {
        	InputStream is = new FileInputStream(exelFileName);
        	HSSFWorkbook excelBook = new HSSFWorkbook(is);
        	ExcelToHtmlConverter ethc = new ExcelToHtmlConverter(
        			DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
        	ethc.setOutputColumnHeaders(false);
        	ethc.setOutputRowNumbers(false);
        	ethc.processWorkbook(excelBook);
        	 Document htmlDocument = ethc.getDocument();
             ByteArrayOutputStream out = new ByteArrayOutputStream();
             DOMSource domSource = new DOMSource(htmlDocument);
             StreamResult streamResult = new StreamResult(out);
             TransformerFactory tf = TransformerFactory.newInstance();
             Transformer serializer = tf.newTransformer();
             serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
             serializer.setOutputProperty(OutputKeys.INDENT, "yes");
             serializer.setOutputProperty(OutputKeys.METHOD, "html");
             serializer.transform(domSource, streamResult);
             out.close();
             String htmlStr = new String(out.toByteArray());
             htmlStr = htmlStr.replace("<h2>Sheet1</h2>", "")
                              .replace("<h2>Sheet2</h2>", "")
                              .replace("<h2>Sheet3</h2>", "")
                              .replace("<h2>Sheet4</h2>", "")
                              .replace("<h2>Sheet5</h2>", "");
             System.out.println(htmlStr);
             writeFile(htmlStr, htmlFilePath);
		} catch (Exception e) {
			logger.error("excel转html出错",e);
		}finally {
			
		}
    }
    
    /**
     * Word 转为　HTML
     */
    public static void wordToHtml(String wordFileName, String htmlFilePath){
    	ByteArrayOutputStream out = null;
    	try {
    		HWPFDocument wordDoc = new HWPFDocument(new FileInputStream(wordFileName));
    		WordToHtmlConverter wthc = new WordToHtmlConverter(
    				DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
    		wthc.setPicturesManager(new PicturesManager() {
    			@Override
    			public String savePicture(byte[] bytes, PictureType pt, String string, float f, float f1) {
    				return string;
    			}
    		});
    		wthc.processDocument(wordDoc);
    		List<Picture> pics = wordDoc.getPicturesTable().getAllPictures();
    		for (Picture pic : pics) {
    			pic.writeImageContent(new FileOutputStream(pic.suggestFullFileName()));
    		}
    		Document htmlDocument = wthc.getDocument();
    		out = new ByteArrayOutputStream();
    		DOMSource domSource = new DOMSource(htmlDocument);
    		StreamResult streamResult = new StreamResult(out);
    		TransformerFactory tf = TransformerFactory.newInstance();
    		Transformer serializer = tf.newTransformer();
    		serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    		serializer.setOutputProperty(OutputKeys.METHOD, "html");
    		serializer.transform(domSource, streamResult);
    		String htmlStr = new String(out.toByteArray());
    		writeFile(htmlStr, htmlFilePath);
		} catch (Exception e) {
			logger.error("word转html出错",e);
		} finally {
        	CloseUtil.close(out);
        }
    }
    
    private static void writeFile(String content, String path) {
        FileOutputStream fos = null;
        BufferedWriter bw = null;
        try {
        	File file = new File(path);
            fos = new FileOutputStream(file);
            bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));
            bw.write(content);
        } catch (Exception ex) {
        	logger.error("关闭流出错",ex);
        } finally {
        	CloseUtil.close(bw);
        	CloseUtil.close(fos);
        }
    }
    
    public static void htmlToPDF(String htmlFilePath,String pdfFilePath) {
    	com.itextpdf.text.Document document = null;
    	try {
        	document = new com.itextpdf.text.Document(PageSize.A4);
            PdfWriter pdfWriter = PdfWriter.getInstance(document,new FileOutputStream(pdfFilePath));
            document.open();
            document.addAuthor("pdf作者");
            document.addCreator("pdf创建者");
            document.addSubject("pdf主题");
            document.addCreationDate();
            document.addTitle("pdf标题,可在html中指定title");
            XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
            InputStream inputStream=null;
            worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlFilePath.getBytes("UTF-8")),inputStream,Charset.forName("UTF-8"),new XMLWorkerFontProvider(){
            	@Override
            	public Font getFont(String fontname, float size, int style) {
            		if (fontname == null) {
            				fontname = "/fonts/STKAITI.TTF";
            	     }
            	     if (size == 0) {
            	            size = 4;
            	      }
            		return super.getFont(fontname, size, style);
            	}
            });
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
			if(document != null){
				document.close();
			}
		}
    }


}
